package org.uim.cricket.analyzer.parsers.batting.impl;

import java.util.HashMap;

import org.uim.cricket.analyzer.parsers.batting.DidNotBatParsable;
import org.uim.cricket.analyzer.parsers.misc.URLIDParsable;
import org.uim.cricket.analyzer.parsers.misc.URLTitleParsable;
import org.uim.cricket.entities.Player;
import org.uim.cricket.util.HTMLStringUtils;
import org.uim.cricket.util.MyStringUtils;

public class DefaultDidNotBatParser implements DidNotBatParsable {

	private URLTitleParsable titleParser = null;
	private URLIDParsable urlIDParser = null;
	
	public DefaultDidNotBatParser(URLIDParsable theIDParser, URLTitleParsable theUrlTitleParser) {
		this.titleParser = theUrlTitleParser;
		this.urlIDParser = theIDParser;
	}
	
	@Override
	public Player[] parseDidNotBatBatsmans(String source) {
		String[] result = MyStringUtils.splitInBetween(source, "<span>", "</span>");
		Player[] players = new Player[result.length];
		
		for (int i=0;i<result.length;i++) {
			players[i] = getPlayer(result[i]);
		}
		
		return players;
	}

	private Player getPlayer(String src) {
		int pos = src.indexOf('<');
		int epos = src.indexOf('>', pos+1);
		
		String tag = src.substring(pos+1, epos);
		HashMap<String, String> attribs = HTMLStringUtils.getHTMLAttributes(tag);
		
		Player player = new Player();
		if (attribs.containsKey("href")) {
			if (this.urlIDParser != null) {
				player.setId(this.urlIDParser.parseUrlID(attribs.get("href")));
			} else {
				player.setId(attribs.get("href"));
			}
		}
		if (attribs.containsKey("title")) {
			player.setShortName(this.titleParser.parseUrlTitle(attribs.get("title")));
		}
		
		pos = src.lastIndexOf("</a>");
		if (src.indexOf("&dagger;") >= 0) player.setWicketKeeper(true);
		if (src.indexOf('*') >= 0) player.setCaptain(true);
		
		player.setTitleName(src.substring(epos+1, pos));
		
		return player;
	}
	
	public void setTitleParser(URLTitleParsable titleParser) {
		this.titleParser = titleParser;
	}
	
	public URLTitleParsable getTitleParser() {
		return titleParser;
	}
	
	public void setUrlIDParser(URLIDParsable urlIDParser) {
		this.urlIDParser = urlIDParser;
	}
	
	public URLIDParsable getUrlIDParser() {
		return urlIDParser;
	}
	
}
